import React, { useEffect, useMemo } from 'react'
import { Modal, Form, Input, message } from 'antd'
import { $post, $put } from '@js/authRequest'
import { awaitWrap } from '@js/tool'
import style from './Index.module.less'

const { Item, useForm } = Form
const { TextArea } = Input

async function addRequest (caseid, content) {
  const res = await $post('/api/xapc/casenote', { caseid, content })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function updateRequest (id, content) {
  const res = await $put(`/api/xapc/casenote/${id}`, { content })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

async function submitHandle (caseid, editData, content, callback) {
  const h = message.loading('提交中', 120)
  const fn = editData ? updateRequest : addRequest
  const [e] = await awaitWrap(fn(editData ? editData.id : caseid, content))
  h()
  if (e === null) {
    callback()
  }
}

function Main ({ caseid, caseno, editData, visible, hide = () => {}, refreshFn = () => {} }) {
  const [formRef] = useForm()
  const title = useMemo(() => {
    return `${caseno || '无'} - ${editData ? '编辑' : '添加'}便签`
  }, [caseno, editData])
  useEffect(() => {
    if (formRef && !visible) {
      formRef.resetFields()
    }
  }, [formRef, visible])
  useEffect(() => {
    if (visible && formRef && editData) {
      formRef.setFieldsValue({
        content: editData.content
      })
    }
  }, [formRef, visible, editData])
  return (
    <Modal className={style.modal} title={title} visible={visible} onCancel={() => hide()} onOk={() => formRef.submit()} maskClosable={false} forceRender>
      <Form form={formRef} onFinish={(d) => { submitHandle(caseid, editData, d.content, () => { hide(); refreshFn() }) }}>
        <Item name='content' label='内容' rules={[{ required: true, message: '内容不能为空' }]}>
          <TextArea autoSize={{ minRows: 3 }} placeholder='请输入' allowClear />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
